package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 点赞行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDTO dto) {
        // 1. 校验参数
        //获取登录的用户和设备id
        ApUser user = AppThreadLocalUtils.getUser();
        Integer equipmentId = dto.getEquipmentId();
        //调用方法校验用户登录方式  获取行为对象
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), equipmentId);
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "用户未登录也无设备id");
        }
        //点赞需要登录
        if (apBehaviorEntry.getType() == 0) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //校验文章id不能为空 使用注解校验

        //校验点赞方式 只能是0 或 1 使用注解校验

        // 2. 根据当前登录用户id查询行为实体对象
//        Query ref_uid = Query.query(Criteria.where("refId").is(user.getId()));
//        ApBehaviorEntry apBehaviorEntry1 = mongoTemplate.findOne(ref_uid, ApBehaviorEntry.class);

        //查询用户的点赞行为
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId())
                .and("articleId").is(dto.getArticleId()));
        ApLikesBehavior apLikesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);

        // 3. 如果是点赞操作  判断是否已经点过赞

        //查询用户是 否已经点过赞了
        if (apLikesBehavior == null) {
            // 4. 没有点过赞则 像mongo点赞集合中 添加点赞数据
            //创建点赞集合
            ApLikesBehavior newApLikesBehavior = new ApLikesBehavior();
            newApLikesBehavior.setCreatedTime(new Date());  //创建时间
            newApLikesBehavior.setEntryId(apBehaviorEntry.getId());   //行为id
            newApLikesBehavior.setArticleId(dto.getArticleId());  //文章di
            newApLikesBehavior.setType((short) 0);  //文章
            newApLikesBehavior.setOperation((short) 0);   //点赞
            //插入对象
            mongoTemplate.save(newApLikesBehavior);
            return ResponseResult.okResult(newApLikesBehavior);
        }

        // 5. 如果是取消点赞操作  在mongo点赞集合中 删除对应点赞数据
        //取消点赞
        apLikesBehavior.setOperation(dto.getOperation());
        mongoTemplate.save(apLikesBehavior);


        //发送消息到消息队列
        //创建消息实体类
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setType(NewBehaviorDTO.BehaviorType.LIKES);
        mess.setAdd(dto.getOperation() == 0 ? 1 : -1);
        mess.setArticleId(dto.getArticleId());
        //发送消息到消息队列
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        //打印日志
        log.info("点赞行为 发送消息 ==>{}",JSON.toJSONString(mess));


        return ResponseResult.okResult(apLikesBehavior);
    }
}
